package com.mashibing.class07;

import java.util.*;

// 测试链接：https://leetcode.com/problems/binary-tree-level-order-traversal-ii
public class Code01_BinaryTreeLevelOrderTraversalII {
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<>();
        if (root == null) {
            return ans;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size(); // 用来记录当前层次的节点个数
            List<Integer> curAns = new LinkedList<>();
            // 循环遍历queue中的每一个元素
            for (int i = 0; i < size; i++) {
                // 将queue中的元素一个一个弹出
                TreeNode curNode = queue.poll();
                //将当前节点的值加入curAns列表中
                curAns.add(curNode.val);
                // 如果当前节点有左节点 或者 右节点, 则将左右节点加入queue中,功下一次while循环使用.
                if (curNode.left != null) {
                    queue.add(curNode.left);
                }
                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            }
            ans.add(0, curAns);
        }
        return ans;
    }

    public static void main(String[] args) {
        int testTime = 100000;
        long start;
        long end;
        ArrayList<Integer> arrayList = new ArrayList<>();
        start = System.currentTimeMillis();
        for (int i = 0; i < testTime; i++) {
            arrayList.add(0,i);
        }
        end = System.currentTimeMillis();
        System.out.println(end - start);

        LinkedList<Integer> arrayList2 = new LinkedList<>();
        start = System.currentTimeMillis();
        for (int i = 0; i < testTime; i++) {
            arrayList2.add(0,i);
        }
        end = System.currentTimeMillis();
        System.out.println(end - start);
        System.out.println("=====================");
        Stack<Integer> stack = new Stack<>();
        stack.add(1);
        stack.add(2);
        stack.add(3);
        while (!stack.isEmpty()){
            System.out.println(stack.pop());
        }
        System.out.println("============================");
        LinkedList<Integer> s = new LinkedList<>();
        s.addLast(1);
        s.addLast(2);
        s.addLast(3);
        while (!s.isEmpty()){
            System.out.println(s.pollFirst());
        }
    }
}
